import {Controller} from "../type/interfaces.ts";
import { handle } from "../vendor/handle.ts";
import {IpcMainEvent, Menu, MenuItem, MenuItemConstructorOptions} from "electron";
import {viewMap} from "../windows/view/index.js";
import {ViewName} from "../type/const.js";
import {mainWindow} from "../windows/main-window.js";


export default class ViewController implements Controller {

  @handle()
  async setViewBounds(e: IpcMainEvent, bounds: Electron.Rectangle, vType: ViewName) {
    viewMap[vType].setBounds(bounds);
  }


  @handle()
  async openViewDevTool(e: IpcMainEvent, vType: ViewName) {
    if (vType == ViewName.Main) {
      mainWindow.window?.webContents.openDevTools()
      return;
    }
    viewMap[vType].view?.webContents.openDevTools()
  }


  @handle()
  async viewLoadUrl(e: IpcMainEvent, url: string, vType: ViewName): Promise<void> {
    console.log("viewLoadUrl", url, vType);
    viewMap[vType].loadURL(url);
  }

  @handle()
  async closeViewPage(e: IpcMainEvent, vType: ViewName): Promise<void> {
    viewMap[vType].destroyView();
  }

  @handle()
  async webviewUrlContextMenu() {
    const template: Array<MenuItemConstructorOptions | MenuItem> = [
      {
        label: "复制",
        role: "copy",
      },
      {
        label: "粘贴",
        role: "paste",
      },
    ];

    const menu = Menu.buildFromTemplate(template);
    menu.popup();
  }

  @handle()
  async viewGoBack(e: IpcMainEvent, vType: ViewName): Promise<boolean> {
    return viewMap[vType].goBack();
  }

  @handle()
  async viewReload(e: IpcMainEvent, vType: ViewName) {
    await viewMap[vType].reload();
  }

  @handle()
  async viewShow(e: IpcMainEvent, vType: ViewName) {
    viewMap[vType].show();
  }

  @handle()
  async viewHide(e: IpcMainEvent, vType: ViewName) {
    viewMap[vType].hide();
  }



}

export const viewController = new ViewController()